package com.cardbaobao.cardbabyclient.ui.activity;

import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.EventWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.DailyRedEnvelopesAdapter;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.callback.RecycleItemClickedCallback;
import com.cardbaobao.cardbabyclient.controller.CommonJumpController;
import com.cardbaobao.cardbabyclient.model.Banner;
import com.cardbaobao.cardbabyclient.model.HeadCommon;
import com.cardbaobao.cardbabyclient.model.RedEnvelopesList;
import com.cardbaobao.cardbabyclient.model.dao.RedEnvelopesRecordDao;
import com.cardbaobao.cardbabyclient.model.result.HeadCommonResult;
import com.cardbaobao.cardbabyclient.model.result.RedEnvelopesListResult;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ScreenUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.cardbaobao.cardbabyclient.widget.divider.VerticalItemDecoration;
import com.cardbaobao.cardbabyclient.widget.refresh.FooterLoadMore;
import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.stx.xhb.xbanner.XBanner;
import com.sunfusheng.marqueeview.MarqueeView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 9:16.
 */
public class DailyRedEnvelopesActivity extends BaseActivity {
    private static final int PAGE_START = 1;
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.main_appbar)
    AppBarLayout appBarLayout;
    @BindView(R.id.xb_banner)
    XBanner xBanner;
    @BindView(R.id.ll_marquee_container)
    LinearLayout llMarqueeContainer;
    @BindView(R.id.marqueeView)
    MarqueeView marqueeView;
    @BindView(R.id.srLayout)
    SmartRefreshLayout srLayout;
    @BindView(R.id.footerLoadMore)
    FooterLoadMore footerLoadMore;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    private DailyRedEnvelopesAdapter adapter;

    private List<RedEnvelopesList.RedEnvelopes> data;
    private int pageNumber = PAGE_START;//分页页码，从1开始
    private RedEnvelopesListResult listResult;

    private RedEnvelopesRecordDao envelopesRecordDao;
    private List<RedEnvelopesRecordDao.RedEnvelopesRecord> envelopesRecords;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        mCurrentPageId= Self.Page.app_daily_red_envelopers_page;

        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).init();
        initIntent();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //banner宽高比75/28
        int width = ScreenUtil.getScreenWidth(mContext);
        ViewGroup.LayoutParams params = xBanner.getLayoutParams();
        params.height = (int) (width * 28 / 75.0f);
        xBanner.setLayoutParams(params);
        xBanner.setmAutoPalyTime(Constant.BANNER_INTERVAL_TIME);

        envelopesRecordDao = new RedEnvelopesRecordDao();
        envelopesRecords = envelopesRecordDao.getAllRedEnvelopesRecordAsc();
        data = new ArrayList<>();
        adapter = new DailyRedEnvelopesAdapter(data);
        adapter.setRecycleItemClickedCallback(new RecycleItemClickedCallback() {
            @Override
            public void onRecycleItemClicked(int position) {
                RedEnvelopesList.RedEnvelopes envelopes = data.get(position);
                boolean contains = false;
                String id=envelopes.getId();
                for (RedEnvelopesRecordDao.RedEnvelopesRecord record : envelopesRecords) {
                    if (id!=null&&id.equals(record.id)) {
                        contains = true;
                        break;
                    }
                }
                if (!contains&& !TextUtils.isEmpty(id)) {
                    RedEnvelopesRecordDao.RedEnvelopesRecord record =
                            new RedEnvelopesRecordDao.RedEnvelopesRecord(id,
                                    System.currentTimeMillis());
                    envelopesRecordDao.insertRedEnvelopesRecords(record);
                    envelopesRecords.add(record);
                }
                if (!TextUtils.isEmpty(envelopes.getUrl())) {
                    mIntent.setClass(mContext, EventWebViewActivity.class);
                    mIntent.putExtra(EventWebViewActivity.WEB_URL_S, envelopes.getUrl());
                    mIntent.putExtra(EventWebViewActivity.WEB_TITLE_S, envelopes.getName());
                    mIntent.putExtra(EventWebViewActivity.WEB_TYPE_I, 36);
                    mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                    startActivity(mIntent);
                }

            }
        });

        final LinearLayoutManager layoutManager=new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState==RecyclerView.SCROLL_STATE_IDLE){
                    if(layoutManager.findFirstCompletelyVisibleItemPosition()==0){
                        appBarLayout.setExpanded(true,true);
                    }
                }
            }
        });
        VerticalItemDecoration decoration =
                new VerticalItemDecoration(0, DensityUtil.dp2px(mContext, 16.0f));
        recyclerView.addItemDecoration(decoration);

        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                srLayout.setEnableRefresh(verticalOffset==0);
            }
        });

        srLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageNumber++;
                loadRedEnvelopes(pageNumber);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNumber = PAGE_START;
                loadRedEnvelopes(pageNumber);
            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        loadHeaderData();
        loadRedEnvelopes(pageNumber);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_daily_red_envelopes;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (xBanner.getParent() != null) {
            xBanner.startAutoPlay();
        }
        if (marqueeView.getParent() != null) {
            marqueeView.startFlipping();
        }
        GoogleAnalyticsUtil.setScreenName(Google.EVERY_DAY_RED);
        UmengEventUtils.pageEvent(mContext, getString(R.string.event_0x04f));
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (xBanner.getParent() != null) {
            xBanner.stopAutoPlay();
        }
        if (marqueeView.getParent() != null) {
            marqueeView.stopFlipping();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //将要销毁时，向服务器提交数据
        commitRedEnvelopesRecord();
    }


    /**
     * 获取顶部公共数据
     */
    private void loadHeaderData() {
        Observable<String> observable= Api.getCommonHeader(Constant.ZCC0107);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                HeadCommonResult headCommonResult = JsonUtil.json2Object(s, HeadCommonResult.class);
                if (headCommonResult.getCode() == Constant.SUC_CODE) {
                    if (headCommonResult.getData() != null) {
                        //配置轮播图
                        if (headCommonResult.getData().getCarousel_figure_list() != null) {
                            setBannerUi(headCommonResult.getData().getCarousel_figure_list());
                        }
                        //配置跑马灯
                        if (headCommonResult.getData().getMarquee_list() != null) {
                            setMarqueeUi(headCommonResult.getData().getMarquee_list());
                        }
                    }
                } else {
                    ToastUtil.showToast(headCommonResult.getMsg());
                }
            }
        });
    }

    /**
     * 设置轮播数据
     */
    private void setBannerUi(final List<Banner.CarouselFigureListBean> data) {
        xBanner.stopAutoPlay();
        if (data.size() == 0) {
            appBarLayout.removeView(xBanner);
            return;
        }
        xBanner.setData(data, null);
        xBanner.setmAdapter(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                ImageLoaderUtil.displayImage(URLUtil.CBB_IMG_URL + ((Banner.CarouselFigureListBean) model).getImage(),
                        (ImageView) view);
            }
        });
        xBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, int position) {
                Banner.CarouselFigureListBean bean = data.get(position);
                CommonJumpController controller = new CommonJumpController(mContext);
                Map<String, Object> extra = new HashMap<>();
                extra.put(CommonJumpController.FROM_PAGE, "每日红包-banner");
                extra.put(EventWebViewActivity.WEB_TYPE_I, 35);
                controller.bannerJump(bean, extra);
            }
        });
        xBanner.startAutoPlay();
    }

    /**
     * 设置跑马灯数据
     */
    private void setMarqueeUi(final List<HeadCommon.MarqueeListBean> data) {
        if (data.size() == 0) {
            marqueeView.stopFlipping();
            llMarqueeContainer.removeAllViews();
            appBarLayout.removeView(llMarqueeContainer);
            return;
        }
        llMarqueeContainer.setVisibility(View.VISIBLE);
        List<String> dataStr = new ArrayList<>();
        for (int i = 0, size = data.size(); i < size; i++) {
            dataStr.add(data.get(i).getContent());
        }
        marqueeView.setFlipInterval(Constant.MARQUEE_INTERVAL_TIME);
        marqueeView.startWithList(dataStr);
        marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
                HeadCommon.MarqueeListBean bean = data.get(position);
                CommonJumpController controller = new CommonJumpController(mContext);
                Map<String, Object> extra = new HashMap<>();
                extra.put(CommonJumpController.FROM_PAGE, "每日红包-跑马灯");
                extra.put(EventWebViewActivity.WEB_TYPE_I, 37);
                controller.marqueeJump(bean, extra);
            }
        });
    }

    /**
     * 加载红包数据
     */
    private void loadRedEnvelopes(int page) {
        Observable<String> observable=Api.getRedEnvelopes(String.valueOf(page));
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                if (recyclerView.getAdapter() == null) {
                    recyclerView.setAdapter(adapter);
                }
                srLayout.finishRefresh();
                srLayout.finishLoadmore();
                if (pageNumber < listResult.getTotal_page()) {
                    footerLoadMore.setStatePreLoading();
                    srLayout.setLoadmoreFinished(false);
                } else {
                    footerLoadMore.setStateNoMoreData();
                    srLayout.setLoadmoreFinished(true);
                }
            }

            @Override
            public void onError(Throwable e) {
                handlePageWhenFailure();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                listResult = JsonUtil.json2Object(s, RedEnvelopesListResult.class);
                if (listResult != null) {
                    if (listResult.getCode() == Constant.SUC_CODE) {
                        if (listResult.getData() != null) {
                            if (listResult.getData().getLoans_redpacket() != null) {
                                if (pageNumber == PAGE_START) {
                                    data.clear();
                                }
                                data.addAll(listResult.getData().getLoans_redpacket());
                                adapter.notifyDataSetChanged();
                            }
                        }
                    } else {
                        handlePageWhenFailure();
                        ToastUtil.showToast(listResult.getMsg());
                    }
                }
            }
        });
    }

    /**
     * 向服务器提交红包申请记录
     */
    private void commitRedEnvelopesRecord() {
        if (envelopesRecords != null && envelopesRecords.size() > 0) {
            //如果最早点击的一条记录，时间大于等于向服务器提交的间隔时间，向服务器提交数据
            if ((System.currentTimeMillis() - envelopesRecords.get(0).time) >=
                    RedEnvelopesRecordDao.RECORD_COMMIT_INTERVAL) {
                StringBuilder sb = new StringBuilder();
                for (RedEnvelopesRecordDao.RedEnvelopesRecord record : envelopesRecords) {
                    sb.append(record.id);
                    sb.append(",");
                }
                //去除最后一个逗号
                sb.deleteCharAt(sb.lastIndexOf(","));
                Observable<String> observable=Api.commitRedEnvelopsRecord(sb.toString());
                //提交数据前，清空本地库
                envelopesRecordDao.clearRedEnvelopesRecords();
                //不需要处理接口返回的数据
                observable.subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String s) {

                    }
                });
            }
        }
    }

    private void handlePageWhenFailure() {
        //加载出错时，处理分页
        pageNumber--;
        if (pageNumber < PAGE_START) {
            pageNumber = PAGE_START;
        }
    }
}
